<template>
  <div class="form-single-fragment" style="position: relative;">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" size="mini" label-position="right">
      <el-row :gutter="20" class="form-single-info">
        <el-col :span="20">
          <el-row>
            <el-col :span="12">
              <el-form-item label="合同名称" prop="contractName">
                <el-input class="input-item" v-model="ruleForm.contractName" placeholder="请输入" maxlength="20"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位名称" prop="customerId">
                <el-select v-model="ruleForm.customerId" filterable placeholder="请选择">
                  <el-option v-for="(item,index) in customerlist" :key="index"
                    :label="item.custName" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业联系人" prop="contactPerson">
                <el-input class="input-item" v-model="ruleForm.contactPerson" placeholder="请输入" maxlength="8"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="telephone">
                <el-input class="input-item" v-model="ruleForm.telephone" placeholder="请输入" maxlength="11" type='tel' onkeyup="value=value.replace(/[^\d]/g,'')"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="负责人" prop="directorUserId">
                <el-select v-model="ruleForm.directorUserId" placeholder="请选择">
                  <el-option v-for="item in listUsers" :key="item.userId"
                  :label="item.showName" :value="item.userId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="付款方式" prop="paymentMethod">
                <el-select v-model="ruleForm.paymentMethod" placeholder="请选择">
                  <el-option label="一次付清" :value="1"></el-option>
                  <el-option label="两次付清" :value="2"></el-option>
                  <el-option label="三次付清" :value="3"></el-option>
                  <el-option label="四次付清" :value="4"></el-option>
                  <el-option label="五次付清" :value="5"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="签约时间" prop="signingDate">
                <el-date-picker v-model="ruleForm.signingDate" type="date" placeholder="选择日期"
                format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="到期时间" prop="finishDate">
                <el-date-picker v-model="ruleForm.finishDate" type="date" placeholder="选择日期"
                format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="业务类型" prop="businessType">
                <el-cascader v-model="ruleForm.businessType"
                  ref="ref_business"
                  :options="businesstypeTree"
                  :props="businesstProps"
                  :show-all-levels="false"
                  clearable
                  @change="businessChange"></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="businessCode=='ZB'">
              <el-form-item label="签约标段" prop="stageNumber">
                <el-select v-model="ruleForm.stageNumber" multiple collapse-tags placeholder="请选择" @change="selectStageNumber">
                  <el-option label="标段一" :value="1"></el-option>
                  <el-option label="标段二" :value="2"></el-option>
                  <el-option label="标段三" :value="3"></el-option>
                  <el-option label="标段四" :value="4"></el-option>
                  <el-option label="标段五" :value="5"></el-option>
                  <el-option label="标段六" :value="6"></el-option>
                  <el-option label="标段七" :value="7"></el-option>
                  <el-option label="标段八" :value="8"></el-option>
                  <el-option label="标段九" :value="9"></el-option>
                  <el-option label="标段十" :value="10"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同金额(元)" :prop="businessCode=='ZB'?'':'contractAmount'">
                <el-input type="number" class="input-item"
                v-model="ruleForm.contractAmount"
                placeholder="请输入" maxlength="20"
                oninput="if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}if(value<0){value='0'}" :disabled="businessCode=='ZB'?true:false"></el-input>
              </el-form-item>
              <el-table :data="ruleForm.contractStageDtos" size="mini" header-cell-class-name="table-header-gray" v-loading="isShowloading" v-if="businessCode=='ZB'">
                <el-table-column prop="stageNumber" align="center" label="标段">
                  <template slot-scope="scope">标段{{scope.row.stageNumber}}</template>
                </el-table-column>
               <el-table-column prop="createTime" align="center" label="分项合同金额(元)">
                 <template slot="header">
                   <span>分项合同金额(元)<span style="color:red;font-size:16px;">*</span></span>
                 </template>
                 <template slot-scope="scope">
                   <el-form-item class="table_input" :prop="'contractStageDtos.' + scope.$index + '.stageAmount'" :rules="rules.stageAmount">
                     <el-input type="number" class="input-item"
                     v-model="scope.row.stageAmount"
                     placeholder="请输入" maxlength="20"
                     oninput="if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}if(value<0){value='0'}" @input="getstageAmount()"></el-input>
                   </el-form-item>
                 </template>
               </el-table-column>
              </el-table>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属项目" :prop="businessCode=='ZB'?'':'projectId'">
                <el-select v-model="ruleForm.projectId" placeholder="请选择" v-if="businessCode!='ZB'">
                  <el-option v-for="(item,index) in projectlist" :key="index"
                  :label="item.projectName" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-table :data="ruleForm.contractStageDtos" size="mini" style="margin-bottom: 20px;" header-cell-class-name="table-header-gray" v-loading="isShowloading" v-if="businessCode=='ZB'">
                <el-table-column prop="stageNumber" align="center" label="标段">
                  <template slot-scope="scope">标段{{scope.row.stageNumber}}</template>
                </el-table-column>
                <el-table-column prop="projectId" align="center" label="分项所属项目">
                  <template slot="header">
                    <span>分项所属项目<span style="color:red;font-size:16px;">*</span></span>
                  </template>
                  <template slot-scope="scope">
                    <el-form-item class="table_input" :prop="'contractStageDtos.' + scope.$index + '.projectId'" :rules="rules.projectId">
                      <el-select v-model="scope.row.projectId" placeholder="请选择">
                        <el-option v-for="(item,index) in projectlist" :key="index"
                        :label="item.projectName" :value="item.id"></el-option>
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目属性" prop="projectAttribute">
                <el-select v-model="ruleForm.projectAttribute" placeholder="请选择">
                  <el-option label="公司项目" :value="1"></el-option>
                  <el-option label="合作单位" :value="2" v-if="(cooperateFlag==1&&stageFlag==0)||(cooperateFlag==1&&stageFlag==1)"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合作单位" prop="cooperateCompany" v-if="ruleForm.projectAttribute==2&&cooperateFlag==1&&stageFlag==1">
                <el-select v-model="ruleForm.cooperateCompany" placeholder="请选择">
                  <el-option label="物产公司" :value="1"></el-option>
                  <el-option label="刘玲群" :value="2"></el-option>
                  <el-option label="其他单位" :value="3"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="24">
            <el-form-item label="合同附件" prop="fileIds">
              <el-upload class="upload-demo"
                :action="action"
                :on-change="handleSuccess"
                :on-remove="handleRemove"
                :before-upload="beforeAvatarUpload"
                :accept="acceptStr"
                multiple
                :file-list="fileLists">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png/word/pdf/ppt文件，且不超过500MB</div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item style="padding: 20px 0;">
              <el-button @click="onCancel(false)">取消</el-button>
              <el-button type="primary" @click="submitForm()">确定</el-button>
            </el-form-item>
          </el-col>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { Customers } from '@/api/commercial.js';
import { Businesstype } from '@/api/business.js';
import { Contracts, Administration, fileUploadFileDo } from '@/api/projectAdministration.js';
export default {
  name: 'Synopsisadd',
  props: {
    contractId: {
      default: undefined
    }
  },
  data () {
    return {
      loading: false,
      isShowloading: false,
      action: fileUploadFileDo,
      fileLists: [],
      acceptStr: '.doc,.docx,.xls,.xlsx,.jpg,.png,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      tableData: [],
      tableData2: [],
      businessCode: '',
      stageFlag: '',
      cooperateFlag: '',
      businesstypeTree: [],
      businesstProps: {
        value: 'id',
        label: 'businessName',
        children: 'children',
        checkStrictly: true,
        emitPath: false
      },
      listUsers: [],
      customerlist: [],
      projectlist: [],
      situation: 1,
      ruleForm: {
        contractId: '',
        contractName: '',
        customerId: '',
        contactPerson: '',
        telephone: '',
        directorUserId: '',
        paymentMethod: '',
        signingDate: '',
        finishDate: '',
        businessType: '',
        contractAmount: '',
        stageNumber: '',
        contractStageDtos: [],
        projectAttribute: '',
        projectId: '',
        cooperateCompany: '',
        fileIds: ''
      },
      rules: {
        contractName: [{ required: true, message: '请输入', trigger: 'blur' }],
        customerId: [{ required: true, message: '请选择', trigger: 'change' }],
        contactPerson: [{ required: true, message: '请输入', trigger: 'blur' }],
        telephone: [{ required: true, message: '请输入', trigger: 'blur' }],
        directorUserId: [{ required: true, message: '请选择', trigger: 'blur' }],
        paymentMethod: [{ required: true, message: '请输入', trigger: 'blur' }],
        signingDate: [{ required: true, message: '请选择', trigger: 'blur' }],
        finishDate: [{ required: true, message: '请选择', trigger: 'blur' }],
        businessType: [{ required: true, message: '请选择', trigger: 'change' }],
        stageNumber: [{ required: true, message: '请选择', trigger: 'change' }],
        contractAmount: [{ required: true, message: '请输入', trigger: 'blur' }],
        projectAttribute: [{ required: true, message: '请选择', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择', trigger: 'change' }],
        cooperateCompany: [{ required: true, message: '请选择', trigger: 'change' }],
        fileIds: [{ required: true, message: '请输入', trigger: 'blur' }],
        contractId: [{ required: true, message: '请选择', trigger: 'change' }],
        stageAmount: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    };
  },
  created () {
  },
  computed: {
    isEdit () {
      return this.contractId != null && this.contractId !== '';
    }
  },
  mounted () {
    if (this.isEdit) {
      this.loadDetailWidgetData()
    }
    this.loadbusinesstypeTree()
    this.listGroupUser()
    this.loadCustomerList()
  },
  methods: {
    /**
     * 合同简介
     */
    loadDetailWidgetData () {
      let params = {
        id: this.$route.query.contractId
      };
      return new Promise((resolve, reject) => {
        Contracts.detail(this, params).then(res => {
          this.ruleForm = res.data
          this.stageFlag = res.data.stageFlag
          this.cooperateFlag = res.data.cooperateFlag
          this.businessCode = res.data.businessCode
          this.ruleForm.stageNumber = []
          let contractStageVoList = res.data.contractStageVoList
          if (contractStageVoList) {
            contractStageVoList.forEach(item => {
              this.ruleForm.stageNumber.push(item.stageNumber)
            })
            this.ruleForm.contractStageDtos = contractStageVoList
          }
          let file = res.data.contractFileVoList
          if (file.length !== 0) {
            this.fileLists = file.map(item => {
              return {
                name: item.fileName,
                url: item.pdfPath,
                response: {
                  data: item
                }
              }
            })
          }
          this.loadbusinesstypeTree()
          this.loadCustomerList()
          this.loadProjectList()
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 业务类型信息表树形列表
     */
    loadbusinesstypeTree () {
      return new Promise((resolve, reject) => {
        Businesstype.tree(this).then(res => {
          this.businesstypeTree = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    businessChange () {
      let checkedNodes = this.$refs['ref_business'].getCheckedNodes()
      this.businessCode = checkedNodes[0].data.businessCode
      this.stageFlag = checkedNodes[0].data.stageFlag
      this.cooperateFlag = checkedNodes[0].data.cooperateFlag
      this.loadProjectList()
      this.$refs['ref_business'].dropDownVisible = false
    },
    /**
     * 项目列表
     */
    loadProjectList () {
      let params = {
        businessType: this.ruleForm.businessType,
        projectId: this.ruleForm.projectId
      }
      return new Promise((resolve, reject) => {
        Administration.listFor(this, params).then(res => {
          this.projectlist = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 客户列表
     */
    loadCustomerList () {
      let params = ''
      return new Promise((resolve, reject) => {
        Customers.lists(this, params).then(res => {
          this.customerlist = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 人员列表
     */
    listGroupUser () {
      return new Promise((resolve, reject) => {
        Contracts.listForOppoAndContract(this).then(res => {
          this.listUsers = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    // 签约标段
    selectStageNumber (data) {
      let lenght = data.length
      let lenght1 = this.ruleForm.contractStageDtos.length
      if (lenght > lenght1) {
        data.forEach(item => {
          let info = this.ruleForm.contractStageDtos.find(items => {
            return item === items.stageNumber
          })
          if (!info) {
            let Obj = {
              projectId: '',
              stageAmount: '',
              stageNumber: item
            }
            this.ruleForm.contractStageDtos.push(Obj)
          }
        })
      } else {
        this.ruleForm.contractStageDtos.forEach((item, index) => {
          let info = data.find(items => {
            return items === item.stageNumber
          })
          if (!info) {
            this.ruleForm.contractStageDtos.splice(index, 1)
          }
        })
      }
      this.$forceUpdate()
    },
    // 标段总金额（元）
    getstageAmount () {
      let contractStageDtos = this.ruleForm.contractStageDtos
      let stageAmount = 0
      contractStageDtos.forEach(item => {
        stageAmount = Number(stageAmount) + Number(item.stageAmount)
      })
      this.ruleForm.contractAmount = stageAmount;
    },
    /**
     * 上传文件-成功
     */
    handleSuccess (file, fileList) {
      this.fileLists = fileList
    },
    /**
     * 上传文件-删除
     */
    handleRemove (file, fileList) {
      this.fileLists = fileList
    },
    /**
     * 上传图片限制条件
     */
    beforeAvatarUpload (file, fileList) {
      // const isJPG = file.type === 'image/jpeg'
      // const isLt200K = file.size / 1024 < 200
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      //   return false
      // }
      // if (!isLt200K) {
      //   this.$message.error('上传头像图片大小不能超过 200KB!')
      //   return false
      // }
      // return isJPG && isLt200K
    },
    /**
     * 提交表单
     */
    submitForm () {
      if (this.fileLists.length !== 0) {
        let filesnew = []
        this.fileLists.forEach((item) => {
          filesnew.push(item.response.data.fileId)
        })
        this.ruleForm.fileIds = filesnew
      }
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.isShowloading = true;
          let params = {
            updateDto: this.ruleForm
          };
          return new Promise((resolve, reject) => {
            Contracts.update(this, params).then(res => {
              this.$message({
                showClose: true,
                message: '操作成功！',
                type: 'success'
              });
              this.onCancel(true);
            }).catch(e => {
              reject(e);
            });
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    onCancel (isSuccess) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess);
      }
    }
  }
}
</script>

<style scoped>
h4{margin-bottom: 0;}
.table_container{margin: 10px 0;}
.form-single-info{display: flex;justify-content: center;}
.el-form-info{box-shadow: 0 0 10px rgba(0,0,0,0.05);padding: 20px;}
.el-form-info strong{margin: 0 10px;}
.table_input /deep/.el-form-item__content{margin-left: 0 !important;}
.table_input.el-form-item{margin: 12px 0;}
/deep/.el-table{margin: 0 0 0 10px;width: calc(100% - 10px);}
/deep/.el-upload-list{width: 60%;}
</style>
